#!/usr/bin/env node

/**
 * 检查数据库用户权限脚本
 * 用于验证应用连接数据库的用户是否有足够的权限
 */

const { Pool } = require('pg');

// 使用应用配置的连接信息
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT) || 5432,
  database: process.env.DB_NAME || 'bike_wholesale',
  user: process.env.DB_USER || 'postgres',
  password: process.env.DB_PASSWORD || 'password'
};

async function checkPermissions() {
  const pool = new Pool(dbConfig);
  
  try {
    console.log('🔍 检查数据库用户权限...');
    console.log(`📊 连接信息: ${dbConfig.user}@${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`);
    
    // 1. 检查当前用户权限
    const userPerms = await pool.query(`
      SELECT 
        usename as username,
        usesuper as is_superuser,
        usecreatedb as can_create_db
      FROM pg_user 
      WHERE usename = $1
    `, [dbConfig.user]);
    
    console.log('👤 用户信息:');
    console.log(`   用户名: ${userPerms.rows[0]?.username || '未知'}`);
    console.log(`   超级用户: ${userPerms.rows[0]?.is_superuser ? '是' : '否'}`);
    console.log(`   可创建数据库: ${userPerms.rows[0]?.can_create_db ? '是' : '否'}`);
    
    // 2. 检查扩展权限
    const extPerms = await pool.query(`
      SELECT 
        extname as extension_name,
        n.nspname as schema_name
      FROM pg_extension e
      LEFT JOIN pg_namespace n ON e.extnamespace = n.oid
      WHERE extname IN ('uuid-ossp', 'pgcrypto')
    `);
    
    console.log('🔧 已安装扩展:');
    extPerms.rows.forEach(ext => {
      console.log(`   ${ext.extension_name} (schema: ${ext.schema_name})`);
    });
    
    // 3. 检查表权限
    const tablePerms = await pool.query(`
      SELECT 
        table_name,
        privilege_type
      FROM information_schema.table_privileges 
      WHERE grantee = $1 
        AND table_schema = 'public'
    `, [dbConfig.user]);
    
    console.log('📋 表权限:');
    const permissionsByTable = {};
    tablePerms.rows.forEach(perm => {
      if (!permissionsByTable[perm.table_name]) {
        permissionsByTable[perm.table_name] = [];
      }
      permissionsByTable[perm.table_name].push(perm.privilege_type);
    });
    
    Object.entries(permissionsByTable).forEach(([table, perms]) => {
      console.log(`   ${table}: ${perms.join(', ')}`);
    });
    
    // 4. 测试扩展功能
    console.log('🧪 测试扩展功能:');
    try {
      const uuidTest = await pool.query('SELECT uuid_generate_v4() as test_uuid');
      console.log(`   ✅ uuid_generate_v4() 功能正常: ${uuidTest.rows[0].test_uuid}`);
    } catch (error) {
      console.log(`   ❌ uuid_generate_v4() 功能失败: ${error.message}`);
    }
    
    // 5. 检查连接池权限
    try {
      const poolTest = await pool.query('SELECT 1 as connection_test');
      console.log(`   ✅ 数据库连接正常`);
    } catch (error) {
      console.log(`   ❌ 数据库连接失败: ${error.message}`);
    }
    
    console.log('\n📊 权限检查完成');
    
  } catch (error) {
    console.error('❌ 权限检查失败:', error.message);
  } finally {
    await pool.end();
  }
}

// 运行检查
if (require.main === module) {
  checkPermissions().catch(console.error);
}

module.exports = { checkPermissions };